class Role < ActiveRecord::Base
  VALID_LABEL = /^[\w\_]{1,40}$/
  
  validates_uniqueness_of :label
  validates_format_of :label, :with => VALID_LABEL

  has_many :user
  
  class << self
    def clear_cache
      @role_cache_list = nil
    end
    
    def role_cache
      @role_cache_list ||= Role.find(:all).inject({}) {|hash, role| hash[role.label.downcase.to_sym] = role; hash}
    end
    
    def list
      role_cache.values
    end

    def selectable
      list - [Role.superadmin]
    end
    
    def get(role_label)
      role_cache[role_label.to_sym]
    end
    
    def method_missing(method_id, *arguments)
      if role = get(method_id)
        role
      else
        super
      end
    end
  end
end
